package service.state;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import service.CommonServlet;

public class GetStatePic extends CommonServlet {

	@Override
	protected void execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try
		{
			String sIdString = request.getParameter("sId");
			if(sIdString==null) throw new Exception("sId can not be empty.");
			int sId = Integer.parseInt(sIdString);
			
			String sql="select * from state_mess where s_id = ?";
			PreparedStatement pstmt = mConnection.prepareStatement(sql);
			pstmt.setInt(1, sId);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next() && rs.getString("p_data")!=null )
			{
				int s_uNo = rs.getInt("u_no");
				String h_data = rs.getString("p_data");
				String photoPath = mPhotoRootPath + s_uNo + File.separator + "pic" + File.separator + h_data;
				OutputStream os = response.getOutputStream();
				FileInputStream fis = new FileInputStream(photoPath);
				byte[] buffer = new byte[8192];
				int n = 0;
				while ( (n = fis.read(buffer)) > 0 )
				{
					os.write(buffer, 0, n);
				}				
			}
			
			
//			OutputStream os = response.getOutputStream();
//			FileInputStream fis = new FileInputStream("C:\\exp5\\head1.gif");
//			byte[] buffer = new byte[8192];
//			int n = 0;
//			while ( (n = fis.read(buffer)) > 0 )
//			{
//				os.write(buffer, 0, n);
//			}
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
			//response.getWriter().println(e.getMessage());
		}
	}

	/**
	 * Constructor of the object.
	 */
	public GetStatePic() {
		super();
	}

}
